/**
 * 监控和健康检查路由
 * EndoSight-UC 医疗AI系统
 *
 * 提供Prometheus指标、健康检查和系统监控端点
 */

import express from 'express';
import winston from 'winston';
import {
  generatePrometheusMetrics,
  getMetricsSummary,
  startSystemMetricsCollection,
  stopSystemMetricsCollection
} from '../utils/metrics.js';
import {
  performDeepHealthCheck,
  getHealthHistory,
  getHealthTrend,
  HealthStatus
} from '../utils/healthChecker.js';
import alertSystem from '../utils/alertSystem.js';
import { withCircuitBreaker } from '../middleware/errorHandler.js';
import { authenticateToken, optionalAuth } from '../middleware/auth.js';

const router = express.Router();

// 配置日志记录器
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.simple()
    })
  ]
});

// 启动系统指标收集
startSystemMetricsCollection(30000); // 每30秒收集一次

// 启动智能告警系统
alertSystem.start(60000); // 每分钟检查一次

/**
 * GET /api/metrics - Prometheus指标端点
 * 提供Prometheus格式的监控指标
 */
router.get('/metrics', optionalAuth, async (req, res) => {
  try {
    const metrics = generatePrometheusMetrics();

    res.set({
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': '0'
    });

    res.send(metrics);

  } catch (error) {
    logger.error('生成指标失败:', error);
    res.status(500).json({
      success: false,
      message: '指标生成失败',
      error: error.message
    });
  }
});

/**
 * GET /api/metrics/summary - 指标摘要端点
 * 提供指标的基本统计信息
 */
router.get('/metrics/summary', optionalAuth, async (req, res) => {
  try {
    const summary = getMetricsSummary();

    res.json({
      success: true,
      data: summary,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    logger.error('获取指标摘要失败:', error);
    res.status(500).json({
      success: false,
      message: '获取指标摘要失败',
      error: error.message
    });
  }
});

/**
 * GET /api/health - 基础健康检查端点
 * 快速健康状态检查，适用于负载均衡器
 */
router.get('/health', optionalAuth, async (req, res) => {
  try {
    // 快速检查核心组件
    const quickCheck = await performDeepHealthCheck({
      includeAI: false,
      includeFileSystem: false,
      includeMetrics: false,
      timeout: 5000
    });

    const statusCode = quickCheck.status === HealthStatus.CRITICAL ? 503 :
                     quickCheck.status === HealthStatus.UNHEALTHY ? 503 :
                     quickCheck.status === HealthStatus.DEGRADED ? 200 : 200;

    res.status(statusCode).json({
      success: quickCheck.status !== HealthStatus.CRITICAL,
      status: quickCheck.status,
      timestamp: quickCheck.timestamp,
      overall_score: quickCheck.overallScore,
      components: Object.keys(quickCheck.components).length,
      alerts_count: quickCheck.alerts.length
    });

  } catch (error) {
    logger.error('基础健康检查失败:', error);
    res.status(503).json({
      success: false,
      status: 'unhealthy',
      timestamp: new Date().toISOString(),
      error: error.message
    });
  }
});

/**
 * GET /api/health/deep - 深度健康检查端点
 * 全面的系统健康状态检查
 */
router.get('/health/deep', authenticateToken, async (req, res) => {
  try {
    const deepCheck = await performDeepHealthCheck({
      includeDatabase: true,
      includeAI: true,
      includeFileSystem: true,
      includeMetrics: true,
      timeout: 30000
    });

    const statusCode = deepCheck.status === HealthStatus.CRITICAL ? 503 :
                     deepCheck.status === HealthStatus.UNHEALTHY ? 503 :
                     deepCheck.status === HealthStatus.DEGRADED ? 200 : 200;

    res.status(statusCode).json({
      success: deepCheck.status !== HealthStatus.CRITICAL,
      data: deepCheck
    });

  } catch (error) {
    logger.error('深度健康检查失败:', error);
    res.status(503).json({
      success: false,
      message: '深度健康检查失败',
      error: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * GET /api/health/components - 组件健康状态端点
 * 检查特定组件的健康状态
 */
router.get('/health/components/:componentName', authenticateToken, async (req, res) => {
  try {
    const { componentName } = req.params;
    const validComponents = ['database', 'ai_service', 'filesystem', 'system_resources', 'application'];

    if (!validComponents.includes(componentName)) {
      return res.status(400).json({
        success: false,
        message: '无效的组件名称',
        valid_components: validComponents
      });
    }

    const options = {
      includeDatabase: componentName === 'database',
      includeAI: componentName === 'ai_service',
      includeFileSystem: componentName === 'filesystem',
      includeMetrics: false,
      timeout: 10000
    };

    const healthCheck = await performDeepHealthCheck(options);

    if (healthCheck.components[componentName]) {
      res.json({
        success: true,
        data: healthCheck.components[componentName],
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(404).json({
        success: false,
        message: '组件检查结果不存在',
        component: componentName
      });
    }

  } catch (error) {
    logger.error(`组件健康检查失败 (${req.params.componentName}):`, error);
    res.status(500).json({
      success: false,
      message: '组件健康检查失败',
      error: error.message
    });
  }
});

/**
 * GET /api/health/history - 健康检查历史端点
 * 获取健康检查的历史记录
 */
router.get('/health/history', authenticateToken, async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 50;
    const history = getHealthHistory(limit);

    res.json({
      success: true,
      data: {
        history,
        total: history.length,
        limit
      },
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    logger.error('获取健康检查历史失败:', error);
    res.status(500).json({
      success: false,
      message: '获取健康检查历史失败',
      error: error.message
    });
  }
});

/**
 * GET /api/health/trend - 健康趋势端点
 * 获取指定时间范围内的健康趋势
 */
router.get('/health/trend', authenticateToken, async (req, res) => {
  try {
    const hours = parseInt(req.query.hours) || 24;
    const trend = getHealthTrend(hours);

    // 计算趋势统计
    const stats = {
      total: trend.length,
      healthy: trend.filter(t => t.status === HealthStatus.HEALTHY).length,
      degraded: trend.filter(t => t.status === HealthStatus.DEGRADED).length,
      unhealthy: trend.filter(t => t.status === HealthStatus.UNHEALTHY).length,
      critical: trend.filter(t => t.status === HealthStatus.CRITICAL).length,
      avgScore: trend.length > 0 ? Math.round(trend.reduce((sum, t) => sum + t.score, 0) / trend.length) : 0
    };

    res.json({
      success: true,
      data: {
        trend,
        stats,
        timeRange: `${hours} hours`
      },
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    logger.error('获取健康趋势失败:', error);
    res.status(500).json({
      success: false,
      message: '获取健康趋势失败',
      error: error.message
    });
  }
});

/**
 * GET /api/monitoring/status - 监控系统状态端点
 * 检查监控系统本身的运行状态
 */
router.get('/status', authenticateToken, async (req, res) => {
  try {
    const status = {
      metrics_collector: {
        active: true,
        last_collection: new Date().toISOString()
      },
      health_checker: {
        active: true,
        history_size: getHealthHistory().length
      },
      circuit_breakers: {
        // 这里可以添加熔断器状态检查
        status: 'operational'
      },
      uptime: process.uptime(),
      memory_usage: process.memoryUsage(),
      timestamp: new Date().toISOString()
    };

    res.json({
      success: true,
      data: status
    });

  } catch (error) {
    logger.error('获取监控系统状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取监控系统状态失败',
      error: error.message
    });
  }
});

/**
 * POST /api/monitoring/refresh - 手动刷新指标端点
 * 手动触发系统指标收集
 */
router.post('/refresh', authenticateToken, async (req, res) => {
  try {
    const { includeSystem = true, includeDeep = false } = req.body;

    if (includeSystem) {
      const { collectSystemMetrics } = await import('../utils/metrics.js');
      await collectSystemMetrics();
    }

    if (includeDeep) {
      await performDeepHealthCheck({
        includeDatabase: true,
        includeAI: true,
        includeFileSystem: true,
        includeMetrics: true,
        timeout: 15000
      });
    }

    res.json({
      success: true,
      message: '指标刷新完成',
      timestamp: new Date().toISOString(),
      refreshed: {
        system_metrics: includeSystem,
        deep_health_check: includeDeep
      }
    });

  } catch (error) {
    logger.error('手动刷新指标失败:', error);
    res.status(500).json({
      success: false,
      message: '指标刷新失败',
      error: error.message
    });
  }
});

/**
 * GET /api/monitoring/alerts - 告警信息端点
 * 获取当前系统的告警信息
 */
router.get('/alerts', authenticateToken, async (req, res) => {
  try {
    const healthCheck = await performDeepHealthCheck({
      includeDatabase: true,
      includeAI: true,
      includeFileSystem: false,
      includeMetrics: false,
      timeout: 10000
    });

    // 按严重程度分类告警
    const alerts = {
      critical: healthCheck.alerts.filter(alert => alert.severity === 'critical'),
      warning: healthCheck.alerts.filter(alert => alert.severity === 'warning'),
      info: healthCheck.alerts.filter(alert => alert.severity === 'info')
    };

    res.json({
      success: true,
      data: {
        alerts,
        total: healthCheck.alerts.length,
        summary: {
          critical: alerts.critical.length,
          warning: alerts.warning.length,
          info: alerts.info.length
        },
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('获取告警信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取告警信息失败',
      error: error.message
    });
  }
});

/**
 * GET /api/monitoring/dashboards - 监控面板信息端点
 * 为前端监控面板提供数据
 */
router.get('/dashboards', authenticateToken, async (req, res) => {
  try {
    const [healthCheck, metricsSummary] = await Promise.all([
      performDeepHealthCheck({
        includeDatabase: true,
        includeAI: true,
        includeFileSystem: true,
        includeMetrics: true,
        timeout: 15000
      }),
      getMetricsSummary()
    ]);

    const dashboardData = {
      overview: {
        overall_status: healthCheck.status,
        overall_score: healthCheck.overallScore,
        uptime: process.uptime(),
        alerts_count: healthCheck.alerts.length,
        recommendations_count: healthCheck.recommendations.length
      },
      components: Object.entries(healthCheck.components).map(([name, component]) => ({
        name,
        status: component.status,
        response_time: component.responseTime,
        alerts_count: component.alerts ? component.alerts.length : 0
      })),
      metrics: metricsSummary,
      alerts: healthCheck.alerts.slice(0, 10), // 只返回最近10个告警
      recommendations: healthCheck.recommendations.slice(0, 5), // 只返回前5个建议
      timestamp: new Date().toISOString()
    };

    res.json({
      success: true,
      data: dashboardData
    });

  } catch (error) {
    logger.error('获取监控面板数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取监控面板数据失败',
      error: error.message
    });
  }
});

// ==================== 智能告警系统端点 ====================

/**
 * GET /api/monitoring/alerts/active - 获取活跃告警
 */
router.get('/alerts/active', authenticateToken, async (req, res) => {
  try {
    const activeAlerts = alertSystem.getActiveAlerts();

    // 按严重程度分类
    const categorized = {
      emergency: activeAlerts.filter(alert => alert.severity === alertSystem.AlertSeverity.EMERGENCY),
      critical: activeAlerts.filter(alert => alert.severity === alertSystem.AlertSeverity.CRITICAL),
      warning: activeAlerts.filter(alert => alert.severity === alertSystem.AlertSeverity.WARNING),
      info: activeAlerts.filter(alert => alert.severity === alertSystem.AlertSeverity.INFO)
    };

    res.json({
      success: true,
      data: {
        alerts: activeAlerts,
        summary: {
          total: activeAlerts.length,
          emergency: categorized.emergency.length,
          critical: categorized.critical.length,
          warning: categorized.warning.length,
          info: categorized.info.length
        },
        categorized,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('获取活跃告警失败:', error);
    res.status(500).json({
      success: false,
      message: '获取活跃告警失败',
      error: error.message
    });
  }
});

/**
 * GET /api/monitoring/alerts/history - 获取告警历史
 */
router.get('/alerts/history', authenticateToken, async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 100;
    const severity = req.query.severity;
    const type = req.query.type;

    let history = alertSystem.getAlertHistory(limit);

    // 过滤条件
    if (severity) {
      history = history.filter(alert => alert.severity === severity);
    }
    if (type) {
      history = history.filter(alert => alert.type === type);
    }

    res.json({
      success: true,
      data: {
        history,
        total: history.length,
        limit,
        filters: { severity, type }
      },
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    logger.error('获取告警历史失败:', error);
    res.status(500).json({
      success: false,
      message: '获取告警历史失败',
      error: error.message
    });
  }
});

/**
 * POST /api/monitoring/alerts/:alertId/acknowledge - 确认告警
 */
router.post('/alerts/:alertId/acknowledge', authenticateToken, async (req, res) => {
  try {
    const { alertId } = req.params;
    const userId = req.user?.doctor_id || 'unknown';

    const success = alertSystem.acknowledgeAlert(alertId, userId);

    if (success) {
      res.json({
        success: true,
        message: '告警已确认',
        data: {
          alertId,
          acknowledgedBy: userId,
          acknowledgedAt: new Date().toISOString()
        }
      });
    } else {
      res.status(404).json({
        success: false,
        message: '告警不存在或无法确认',
        alertId
      });
    }

  } catch (error) {
    logger.error('确认告警失败:', error);
    res.status(500).json({
      success: false,
      message: '确认告警失败',
      error: error.message
    });
  }
});

/**
 * POST /api/monitoring/alerts/:alertId/resolve - 解决告警
 */
router.post('/alerts/:alertId/resolve', authenticateToken, async (req, res) => {
  try {
    const { alertId } = req.params;

    const success = alertSystem.resolveAlert(alertId);

    if (success) {
      res.json({
        success: true,
        message: '告警已解决',
        data: {
          alertId,
          resolvedAt: new Date().toISOString()
        }
      });
    } else {
      res.status(404).json({
        success: false,
        message: '告警不存在或无法解决',
        alertId
      });
    }

  } catch (error) {
    logger.error('解决告警失败:', error);
    res.status(500).json({
      success: false,
      message: '解决告警失败',
      error: error.message
    });
  }
});

/**
 * POST /api/monitoring/alerts/test - 创建测试告警
 */
router.post('/alerts/test', authenticateToken, async (req, res) => {
  try {
    const { type = 'system_health', severity = 'warning', title, message } = req.body;

    const testAlert = await alertSystem.createAlert(
      type,
      severity,
      title || '测试告警',
      message || '这是一个手动创建的测试告警',
      {
        isTest: true,
        createdBy: req.user?.doctor_id || 'unknown',
        timestamp: new Date().toISOString()
      }
    );

    res.json({
      success: true,
      message: '测试告警创建成功',
      data: testAlert.toJSON()
    });

  } catch (error) {
    logger.error('创建测试告警失败:', error);
    res.status(500).json({
      success: false,
      message: '创建测试告警失败',
      error: error.message
    });
  }
});

/**
 * GET /api/monitoring/alerts/statistics - 告警统计信息
 */
router.get('/alerts/statistics', authenticateToken, async (req, res) => {
  try {
    const activeAlerts = alertSystem.getActiveAlerts();
    const history = alertSystem.getAlertHistory(1000); // 获取更多历史数据用于统计

    // 按类型统计
    const typeStats = {};
    // 按严重程度统计
    const severityStats = {};
    // 按状态统计
    const statusStats = {};

    activeAlerts.forEach(alert => {
      typeStats[alert.type] = (typeStats[alert.type] || 0) + 1;
      severityStats[alert.severity] = (severityStats[alert.severity] || 0) + 1;
      statusStats[alert.status] = (statusStats[alert.status] || 0) + 1;
    });

    // 计算趋势（最近24小时）
    const now = Date.now();
    const last24h = history.filter(alert =>
      now - new Date(alert.timestamp).getTime() <= 24 * 60 * 60 * 1000
    );

    const hourlyTrend = Array.from({ length: 24 }, (_, i) => {
      const hourStart = now - (i + 1) * 60 * 60 * 1000;
      const hourEnd = now - i * 60 * 60 * 1000;

      const alertsInHour = last24h.filter(alert => {
        const alertTime = new Date(alert.timestamp).getTime();
        return alertTime >= hourStart && alertTime < hourEnd;
      });

      return {
        hour: new Date(hourStart).toISOString(),
        count: alertsInHour.length,
        critical: alertsInHour.filter(a => a.severity === 'critical').length,
        warning: alertsInHour.filter(a => a.severity === 'warning').length
      };
    }).reverse();

    res.json({
      success: true,
      data: {
        current: {
          total: activeAlerts.length,
          byType: typeStats,
          bySeverity: severityStats,
          byStatus: statusStats
        },
        trend: {
          last24h: last24h.length,
          hourly: hourlyTrend
        },
        topAlertTypes: Object.entries(typeStats)
          .sort(([,a], [,b]) => b - a)
          .slice(0, 5)
          .map(([type, count]) => ({ type, count })),
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    logger.error('获取告警统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取告警统计失败',
      error: error.message
    });
  }
});

/**
 * GET /api/monitoring/alerts/config - 获取告警配置
 */
router.get('/alerts/config', authenticateToken, async (req, res) => {
  try {
    const config = {
      thresholds: {
        responseTime: {
          warning: 1000,
          critical: 3000
        },
        errorRate: {
          warning: 0.05,
          critical: 0.15
        },
        memoryUsage: {
          warning: 0.80,
          critical: 0.95
        },
        cpuUsage: {
          warning: 0.70,
          critical: 0.90
        }
      },
      suppression: {
        sameAlertSuppression: 300000, // 5分钟
        alertStormThreshold: 10,
        alertStormWindow: 600000 // 10分钟
      },
      status: {
        isRunning: alertSystem.alertManager?.isRunning || false,
        registeredHandlers: alertSystem.alertManager?.alertHandlers?.length || 0
      },
      timestamp: new Date().toISOString()
    };

    res.json({
      success: true,
      data: config
    });

  } catch (error) {
    logger.error('获取告警配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取告警配置失败',
      error: error.message
    });
  }
});

export default router;